package com.zcsy.manage.web.base;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.ShopCatagoryView;
import com.zcsy.manage.model.base.ShopCategory;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.base.ShopCategoryDao;
import com.zcsy.manage.service.base.IShopCategoryService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * 
 * @Title: ShopCategoryController.java
 * @Package： com.zcsy.manage.web.base
 * @Description: 商户分类控制层
 * @author zhangsh zsh3384027@gmail.com
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 * @date 2016年4月12日
 * @version 1.0
 * @see JDK1.8.0_45
 * @since
 */
@Controller
@RequestMapping(value = "/shopcategory")
public class ShopCategoryController {

	@Autowired
	private IShopCategoryService shopCategoryService;

	@Autowired
	private ShopCategoryDao shopCategoryDao;

	@Autowired
	private IDictService dictService;
	
	/**
	 * 
	 * @Description 根据分类名称/等级 查询获取商户分类列表
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月12日
	 * @see
	 */
	@RequestMapping(value = "/shopCategoryList", method = RequestMethod.GET)
	public String getShopCategoryList(Model model, Integer pNo, Integer pSize, String name,
			String level, HttpServletRequest req) {

		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);
		ShopCategory shopCategory = new ShopCategory();

		if (StringUtils.isNotEmpty(name)) {
			shopCategory.setName(name);
		}

		if (StringUtils.isNotEmpty(level)) {
			shopCategory.setLevel(Integer.parseInt(level));
		}

		List<ShopCatagoryView> shopCategoryviewList = shopCategoryService
				.selectByKeyword(shopCategory);
		PageInfo<ShopCatagoryView> unit = new PageInfo<ShopCatagoryView>(
				shopCategoryviewList);

		model.addAttribute("shopCategorys", unit);
		model.addAttribute("shopCategoryName", name);
		model.addAttribute("level", level);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "base/shopcategory/shopCategoryList";
	}

	/**
	 * 
	 * @Description 新增或编辑
	 * @param model
	 * @param id
	 *            主键id，id=0新增，id!=0编辑
	 * @return
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月9日
	 * @see
	 */
	@RequestMapping(value = "/editshopcategory")
	public String editshopUnit(Model model, String id, HttpServletRequest req) {
		
		try {
			if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				model.addAttribute("type", Constants.SAVE_TYPE);
				
			} else {
				ShopCategory shopCategory = shopCategoryService
						.selectByPrimaryKey(id);
			/*	ShopCategory parentCategory = shopCategoryService
						.selectByPrimaryKey(shopCategory.getParentId());*/
				if (shopCategory != null) {
					model.addAttribute("type", Constants.EDIT_TYPE);
					model.addAttribute("shopCategory", shopCategory);
//					model.addAttribute("parentCategory", parentCategory);
				}
			}
		} catch (Exception e) {
		}
		
		return "base/shopcategory/shopCategoryEdit";
	}

	/**
	 * 
	 * @Description 根据level 获取上级分类
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月13日
	 * @see
	 */
	@RequestMapping(value = "/getParentBylevel")
	@ResponseBody
	public RequestJson getRegionByCellId(String categorylevel, HttpServletRequest req) {
		RequestJson result = new RequestJson();
		try {
			if (StringUtils.isNotEmpty(categorylevel)) {
				List<ShopCategory> shopCategory = new ArrayList<ShopCategory>();
				shopCategory = shopCategoryService.getParentBylevel(Integer
						.parseInt(categorylevel) - 1);
				result.setObj(shopCategory);
				result.setSuccess(true);
			} else {
				result.setSuccess(false);
			}
		} catch (Exception e) {
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * @Description 保存编辑商户分类
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月13日
	 * @see
	 */
	@RequestMapping(value = "/saveOrUpdateshopcategory", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson saveOrUpdate(Model model, String id, String name,
			String level, String parentId, String logo, Integer sort,
			String describe, String memo, HttpServletRequest req) {
		
		RequestJson result = new RequestJson();
		ShopCategory shopCategory = new ShopCategory();
		User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		
		shopCategory.setName(name);
		
		if (StringUtils.isNotEmpty(level)) {
			shopCategory.setLevel(Integer.parseInt(level));
		}
		
		shopCategory.setParentId(parentId);
		shopCategory.setLogo(logo);
		shopCategory.setSort(sort);
		shopCategory.setDescrip(describe);
		shopCategory.setMemo(memo);
		shopCategory.setUserAccount(user.getLoginname());
		
		try {
			if (id != null && !"0".equals(id)) {
				shopCategory.setId(id);
				shopCategory.setUpdateTime(new Date());
				shopCategoryService.update(shopCategory);
				LogUtils.insertLog("用户编辑店铺分类信息", user.getId(), req);
			} else {
				shopCategory.setId(UniqueNumberUtils.get18UniqueNumber());
				shopCategory.setSendTime(new Date());
				shopCategoryService.insert(shopCategory);
				LogUtils.insertLog("用户新增店铺分类信息", user.getId(), req);
			}
			result.setSuccess(true);
		} catch (Exception e) {
			result.setMsg("操作失败！");
		}
		return result;
	}

	/**
	 * @Description 批量删除 单元信息
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月9日
	 * @see
	 */
	@RequestMapping(value = "/deleteShopCategory", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson deleteByPrimaryKey(String ids, HttpServletRequest req) {
		
		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		try {
			String keys[] = ids.split("\\,");
			for (int i = 0; i < keys.length; i++) {
				List<ShopCategory> shopCategorys = shopCategoryService
						.getCategoryByparentId(keys[i]);
				ShopCategory shopCategory = shopCategoryService
						.selectByPrimaryKey(keys[i]);
				if (CollectionUtils.isEmpty(shopCategorys)) {
					shopCategoryService.deleteByPrimaryKey(keys[i]);
					result.setSuccess(true);
					LogUtils.insertLog("用户删除店铺分类信息", user.getId(), req);
				} else {
					result.setMsg(shopCategory.getName() + "已被引用，不能删除！");
					result.setSuccess(false);
				}
			}
		} catch (NumberFormatException e) {
			result.setSuccess(false);
			result.setMsg("操作失败");
		}
		return result;
	}

	/**
	 * @Description 商户分类详情
	 * @author zhangsh zsh3384027@gmail.com
	 * @date 2016年4月13日
	 * @see
	 */
	@RequestMapping(value = "/detailShopcategory", method = RequestMethod.GET)
	public String detailShopcategory(Model model, String id, HttpServletRequest req) {
		try {
			ShopCategory shopCategory = shopCategoryService
					.selectByPrimaryKey(id);
			ShopCategory parentCategory = shopCategoryService
					.selectByPrimaryKey(shopCategory.getParentId());
			if (shopCategory != null) {
				model.addAttribute("shopCategory", shopCategory);
				model.addAttribute("parentCategory", parentCategory);
			}
		} catch (Exception e) {
		}
		return "base/shopcategory/shopCategoryDetail";
	}

	/**
	 * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
	 * @param id 商品id
	 * @param req   用户请求
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月3日
	 * @see
	 */
	@RequestMapping(value = "updateSort", method = RequestMethod.GET)
	@ResponseBody
	public RequestJson updateSort(String id, HttpServletRequest req) {
		
		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		try {
			ShopCategory shopCategory = shopCategoryService.selectByPrimaryKey(id);
			if (shopCategory != null) {
				shopCategory.setUpdateTime(DateUtils.getDate());
				shopCategoryDao.updateSort(shopCategory);
				LogUtils.insertLog("用户置顶店铺分类信息", user.getId(), req);
			}
		} catch (Exception e) {
			result.setMsg("操作失败");
			result.setSuccess(false);
		}
		return result;
	}
}
